<?php
/**
 * Created by PhpStorm.
 * User: tlb
 * Date: 2019/3/24
 * Time: 12:07 PM
 */

namespace App\Http\Controllers\AppApi\Home;


use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\Admin\CompanyModel;
use App\Models\Admin\JobCompanyModel;
use App\Models\Admin\OrderBaleModel;
use App\Models\JobsCompanysModel;
use App\Models\JobsModel;
use App\Models\LogModel;
use App\Models\User\UsergongchangModel;
use App\Models\User\UserGongsiModel;
use App\Models\User\UserLevelModel;
use App\Repositories\Admin\JobCompanyRepository;
use App\Repositories\Admin\OrderBaleRepository;
use App\Repositories\JobsRepository;
use App\Services\Admin\OrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ReleaseController extends BaseController
{
    private $jobRepository;
    private $orderService;
    private $orderBaleRepository;
    protected $jobCom;

    public function __construct(
        JobsRepository $jobsRepository,
        OrderBaleRepository $orderBaleRepository,
        OrderService $orderService
    )
    {
        parent::__construct();
        $this->orderBaleRepository = $orderBaleRepository;
        $this->jobRepository = $jobsRepository;
        $this->orderService = $orderService;
        $this->jobCom = new JobCompanyRepository();
    }

    //检查权限
    protected function checkToken(Request $request)
    {
        $token = $request->request->get('token');
        if (empty($token)) {
            return false;
        }
        $uid = $this->accessGet($token);
        if (empty($uid)) {
            return false;
        }
        $this->uid = $uid;
        return true;
    }

    /**
     * 发布招聘信息
     */
    public function recruit(Request $request)
    {
      //  LogModel::add(json_encode($request->toArray()),LogModel::typeinfo,'api/home/release/recruit');
       /// $token = $request->token;
       /* if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet();//$token
        $rule = [
            'job' => 'required|integer',
            'num' => 'required|integer',
            'emolument' => 'required',//薪酬  integer
            'welfare' => 'required|integer',//福利待遇：0，暂无；1，包住；2，包吃；
            'rest' => 'required|integer', //休息制度：1，单休；2，双休
            'education' => 'required|integer', //学历：1，小学；2初中；3，高中；4，大专；5，本科；6，研究生；7，其他
            'work_year' => 'required|integer', //工作年限：1，一年以内；2，1至2年；3，3至5年；4，5年以上
            'address' => 'required', //工作地点
            'detail' => 'required', //岗位类型
            'content' => 'required', //工作内容
            'work_hour' => 'required', //'工作时间'
            'contact_name' => 'required', //'联系人姓名
            'contact_telephone' => 'required', //联系人号码
            'email' => 'required|email', //邮箱
            'sex' => 'required|integer',//性别1男，2女
            'age_range' => 'required',//年龄区间，英文逗号隔开,
            'skill' => 'required',//技术工种
            'company_name' => 'required',//技术工种

        ];
        $this->validate($request, $rule);
        $data = $request->post();
        //print_r($data);exit;
       /* if ($data['emolument'] > 65530) {
            return $this->toJson(-2);
        }*/
        unset($data['token']);
        unset($data['app_access']);
        unset($data['job_name']);
        unset($data['age_range1']);
        unset($data['age_range2']);
        $data['cid'] = $uid;
        $addData = [];
        foreach (array_keys($rule) as $item) {
            $addData[$item] = $data[$item];
        }
        $data['status'] =JobsCompanysModel::status_fabuzhong;
        $imgDetails=$request->post('imgDetails',null);
      /// ;; print_r($imgDetails);exit;
        if($imgDetails){
            $data['imgDetails'] =$imgDetails;//json_encode($imgDetails);
        }else{
            $data['imgDetails'] = '';
        }
        if(empty($data['id'])){
            $lastId = $this->jobCom->setAdd($data);
        }else{
            $id=$data['id'];
            $one=JobCompanyModel::where(['id'=>$id])->first();
            foreach ($data as $k=>$vo){
                $one[$k]=$vo;
            }
            $res=$one->update();
            if($res){
                 return $this->toJson(0,['id'=>$one->id]);
            }else{
                  return $this->toJson(0,[],'出现错误');
            }
        }

        if(!$lastId){
            return $this->toJson(0,[],'出现错误');
        }
      //  LogModel::add('$lastId='.$lastId,LogModel::typeinfo,'api/home/release/recruit');
        return $this->toJson(0,['id'=>$lastId]);
//        $this->jobRepository->addJobsCompany($data);
       //   return $this->output();
    }

    /**
     * 职位列表
     * /api/home/release/job_list
     */
    public function jobList()
    {

        $key = 'ReleaseControllerjobList';
        $data = Cache::remember($key, 10080, function () {
            $positionList = JobsModel::where([['cate', 2], ['pid', 0], ['del', 0]])->get()->toArray();
            $data = [];
            foreach ($positionList as $k => $v) {
                $jobs = JobsModel::where([['cate', 2], ['pid', $v['id']]])->select(['id', 'name'])->get()->toArray();
                $data[$k]['position'] = [];
                $data[$k]['position']['name'] = $v['name'];
                $data[$k]['position']['job'] = $jobs;
            }
            return $data;
        });
        return $this->output($data, 'ok', 200, 200, ['Access-Control-Allow-Origin' => '*']);
    }

    /**
     *  发布订单
     * /api/home/release/order
     */
    public function order(Request $request)
    {
            LogModel::add(json_encode($request->toArray()),LogModel::typeinfo,'api/home/release/order');

        $token = $request->token;
       /* if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet($token);

        $user=OA::$user->getModel();
        if(!$user['is_company']){
            OA::Json(1,'无法发布货单,请到设置打开"启用公司"开关');
        }
        if(empty($request->orderID)){
            return $this->toJson(-2, [], 'orderID参数错误');
        }
        /**
         * @var OrderBaleModel $one;
        */
        $one=OrderBaleModel::where([
            'id'=>$request->orderID,
            'uid'=>$uid
        ])->first();
        if(!$one){
            return $this->toJson(-2, [], '权限错误,或者参数错误');
        }
        if (!UserGongsiModel::infoexists($uid)) {
            return $this->toJson(-2, [], '请填写用户基本信息,才能发布;请完善资料');
        }
       /* if($one->status!=OrderBaleModel::status_weikaishi
            &&$one->status!=OrderBaleModel::status_kaishi){///只允许只等于这两个值
            return $this->toJson(-2, [], '货单状态设置错误');
        }*/
        $rule = [
            'name' => 'required',
            'orderID' => 'required',
            'styleNo' => 'required',
            'styleName' => 'required',
         //   'scence' => 'required',
           //   'status' => 'required',
          //  'material' => 'required',
        //    'tech' => 'required',
            'sizelist' => 'required',
            'num' => 'required',
            'money' => 'required',
            'bond' => 'required',
            'img' => 'required',
            'sizelist' => 'required',
            //'costlist' => 'required',
            'proType' => 'required',
         //   'region' => 'required',
            'proWay' => 'required',
            'deplete' => 'required',
          //  'orderType' => 'required',
            'style' => 'required',
           /// 'design' => 'required',
            'detail' => 'required',
            'cate' => 'required',
            'outTypes' => 'required',
            'isRob' => 'required',
            'isFabric' => 'required',
        ];
        //exit('sssssssssss');





        $this->validate($request, $rule, ['num.integer' => '比如为数字']);
          ///    var_dump($request->design);exit;

        if (!is_numeric($request['num'])) {
            return $this->toJson(-2, [], '数量必须为数字');
        }
        if (!is_numeric($request['money'])) {
            return $this->toJson(-2, [], '金额必须为数字');
        }
        if (!is_numeric($request['bond'])) {
            return $this->toJson(-2, [], '保证金必须为数字');
        }
        if (!Fun::checkDateIsValid($request['period'])) {
            return $this->toJson(-2, [], '截止抢单时间错误');
        }
        if (!Fun::checkDateIsValid($request['complete_time'])) {
            return $this->toJson(-2, [], '最晚完成时间错误');
        }
        $request['period'] = strtotime($request['period']);
        if ($request['period'] <= time()) {
            return $this->toJson(-2, [], '截止抢单时间设置必须是大于今天的日期');
        }
        $request['complete_time'] = strtotime($request['complete_time']);
        if ($request['complete_time'] <= time()) {
            return $this->toJson(-2, [], '最晚完成时间设置必须是大于今天的日期');
        }
        $stuffs = array();
        $depletes = array();
        $sizelists = array();
        foreach ($request->stuff as $k => $stuff) {
            $stuffs[$k]['key'] = $stuff['key'] ? $stuff['key'] : '';
            $stuffs[$k]['val'] = $stuff['val'] ? $stuff['val'] : '';
        }
        foreach ($request->deplete as $k => $deplete) {
            $depletes[$k]['name'] = $deplete['name'] ? $deplete['name'] : '';
            $depletes[$k]['size'] = $deplete['size'] ? $deplete['size'] : '';
            $depletes[$k]['num'] = $deplete['num'] ? $deplete['num'] : '';
            $depletes[$k]['remark'] = $deplete['remark'] ? $deplete['remark'] : '';
        }
        /*
        foreach ($request->sizelist as $k => $sizelist) {
            $sizelists[$k]['color'] = $sizelist['color'] ? $sizelist['color'] : '';
            $sizelists[$k]['size'] = $sizelist['size'] ? $sizelist['size'] : '';
            $sizelists[$k]['num'] = $sizelist['num'] ? $sizelist['num'] : '';
        }*/


        if ($request->isRob == '1' && $request->bond <= 0) {
            return $this->toJson(-2, [], '签单类型为:抢单的时候,保证金必须大于0');
        }
        if ($request->isRob == '2' && $request->bond != 0) {
            return $this->toJson(-2, [], '签单类型为:普通单的时候,保证金必须等于0');
        }
        $outTypeStr = $request->outTypes ? implode(',', $request->outTypes) : '';

        $addData = array(
            'uid' => $uid,
            'name' => $request->name,
            'cate' => $request->cate, //订单类型：待修改
            'styleNo' => $request->styleNo,
            'styleName' => $request->styleName,
      //      'scence' => $request->scence,
        //    'material' => $request->material,
         //   'tech' => $request->tech,
            'sizelist' =>$request->sizelist,
           /// 'costlist' =>$request->costlist,
            'num' => $request->num,
            'money' => $request->money,
            'bond' => $request->bond,
          //   'status' => $request->status,
            'img' => $request->img,
            'proType' => $request->proType,
            'juli' => $request->juli,
          //  'region' => $this->getAreaIdByName($request->region),
            'proWay' => $request->proWay,
            'stuff' => json_encode($stuffs),
            'deplete' => json_encode($depletes),
          //  'orderType' => $request->orderType, //产品类型， 待修改
            'style' => $request->style, //产品风格，待修改
          //  'design' => $request->design, //产品款式，待修改
            'period' => $request->period,
            'complete_time' => $request->complete_time,
            'detail' => $request->detail,
            'outTypeStr' => $outTypeStr, //是外发类型，待修改
            'is_rob' => $request->isRob, //是否抢单，待修改
            'is_fabric' => $request->isFabric, //是否抢单，待修改
            'status' => OrderBaleModel::status_weikaishi,//如果未设置合同,先设置未开启抢单
             'visible' => $request->visible//是否显示
        );
       /* if($request->status!=OrderBaleModel::status_weikaishi
            &&$request->status!=OrderBaleModel::status_kaishi){///只允许只等于这两个值
            return $this->toJson(-2, [], '货单状态设置错误');
        }*/

        if(empty($request->imgDetails)){
            $one->imgDetails='';
        }else{
            $one->imgDetails=json_encode($request->imgDetails);
        }
        foreach ($addData as $key=>$vo){
            $one->$key=$vo;
        }
        if($one->created_at==0){
            $one->created_at=time();
        }
        $one->updated_at=time();
        if($one->save()){
            return $this->output(['id' => $one->id]);
        }else{
            OA::Json(1,"保存错误");
        }

      ///  $lastId = $this->orderBaleRepository->setAdd($addData);
        return $this->output(['id' => $request->id]);
    }
    /**
     * 外发类型
     */
    public function getOutTypes(Request $request)
    {
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $type = $request->type;
        $uid = $this->accessGet( );
        if (!$uid) {
            return $this->toJson(-13);
        }
        if ($type == 3) {
            $cateId = 174;
        } else if (in_array($type, [2, 4])) {
            $cateId = 185;
        } else {
            $cateId = 0;
        }
        $dataArr = $this->getSubsByCates(array($cateId));
        if (!$dataArr) {
            return $this->toJson(-3);
        }
        return $this->toJson(0, $dataArr);
    }

    /**
     * 订单类型
     * /api/home/release/cates
     */
    public function getCates(Request $request)
    {
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
      /*  if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet($token);
        if (!$uid) {
            return $this->toJson(-13);
        }
//        $dataArr = $this->getSubsByCates(array(19,20,21));
        $dataArr = $this->getSubsByCates(array(167));
        if (!$dataArr) {
            return $this->toJson(-3);
        }
        return $this->toJson(0, $dataArr);
    }

    /**
     * 招聘表单的选项数据获取
     * made By Jiuge
     */
    public function getOptionList(Request $request)
    {
      ///  exit("逻辑修改,这里弃用");
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
       /* if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet($token);
        if (!$uid) {
            return $this->toJson(-13);
        }
        $names=[];
        $gs=UserGongsiModel::where([
            'uid'=>OA::$user->getId(),
            'shenhe'=>1
        ])->select('com_name')->first();

        $gc=UsergongchangModel::where([
            'uid'=>OA::$user->getId(),
            'shenhe'=>1
        ])->select('com_name')->first();


     //   print_r($gs);exit;
        if(empty($gs)&&empty($gc)){
            return $this->toJson(1, [],'企业资料未审核或者未填写');
        }
        if($gs){
            $names[]=$gs['com_name'];
        }
        if($gc){
            $names[]=$gc['com_name'];
        }
        /*
        foreach ($gs as $g){
            $names[]=$g['com_name'];
        }
        foreach ($gc as $g){
            $names[]=$g['com_name'];
        }*/

        $dataArr = array(
            'welfares' => $this->jobCom->getWelfares(), //福利待遇
            'rests' => $this->jobCom->getRests(), //休息制度
            'edus' => $this->jobCom->getEdus(), //学历
            'workYears' => $this->jobCom->getWorkYears(), //工作年限
            'company_name'=>$names
        );
        return $this->toJson(0, $dataArr);
    }
}